package com.jackchong.base

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.IdRes
import androidx.appcompat.app.AppCompatActivity
import com.jackchong.utils.JAuto
import com.jackchong.utils.ThreadUtils
import me.yokeyword.fragmentation.SupportFragment
import me.yokeyword.fragmentation_swipeback.SwipeBackFragment
import java.lang.Exception

/**
 * author : jack(黄冲)
 * e-mail : 907755845@qq.com
 * create : 2019-10-12
 * desc   :
 */

abstract class BaseSupportFragment : SwipeBackFragment() {


    var mLoaderId : Int = 0
    val mMap = HashMap<String, Any>()
    protected lateinit var mActivity: AppCompatActivity
    protected lateinit var mRootView: View
    var isInitialize = false

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mActivity = context as AppCompatActivity;
    }

    override fun onAttach(activity: Activity) {
        try {
            super.onAttach(activity)
        }catch (e: Exception){

        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        var layoutId = getLayoutId()
        if (getLayoutId() == 0) {
            layoutId = this::class.java.getAnnotation(JLayout::class.java)!!.res
        }

        mRootView = View.inflate(mActivity, layoutId, null)
//        AdaptScreenUtils.adaptWidth(resources, 750)
//        AdaptScreenUtils.adaptHeight(resources, 1333)
        JAuto.auto(mRootView)
        return if (attachToSwipeBack()) {
            attachToSwipeBack(mRootView)
        }else{
            mRootView
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initLayout(view)
        isInitialize = true
    }

    protected fun getLayoutId(): Int = 0

    protected open fun attachToSwipeBack(): Boolean = false

    abstract fun initLayout(view: View)

    fun getSupportFragment() : SupportFragment = parentFragment as SupportFragment

    fun <T : View> findView(@IdRes id: Int): T {
        return mRootView.findViewById(id)
    }

    open fun onReceiveEvent(event: EventMgsBean) {

    }

    fun onSendEvent(event: EventMgsBean) {
        ThreadUtils.post { onReceiveEvent(event) }
    }

}